﻿using System.Collections.Generic;
using System;

namespace sinetd.Services.Chat
{
    public class Service : BaseService, IService
    {
        public Service()
            : base("Chat")
        {
            room = new Dictionary<string, List<string>>();
            room["Default"] = new List<string>();
        }

        private Dictionary<string, List<string>> room;

        private ConnectionPoll connectionPool;

        #region IService Members

        public void HandleNewConnection(IConnectionIO conn)
        {
            if (connectionPool == null) connectionPool = new ConnectionPoll();

            connectionPool.NewConnection(conn);

            if (!connectionPool.IsRunning)
            {
                connectionPool.Handle += new ConnectionPoll.HandleHandler(connectionPool_Handle);   
                connectionPool.Start();
            }
        }

        public void Shutdown()
        {
            if (connectionPool != null)
                if (connectionPool.IsRunning) connectionPool.Stop();
        }

        #endregion

        private void connectionPool_Handle(IConnectionIO iConnectionIO, object p)
        {
            if(p == null)
            {
                WelcomeNewUser(iConnectionIO);
                return;
            }

            string login = (string)p;

            try
            {
                string response = "[Null]";
                string[] msg = connectionPool.GetUserConnection(login).Recv().Split();
                if (msg.Length > 1)
                {
                    switch (msg[0])
                    {
                        case "msg":
                            connectionPool.GetUserConnection(msg[1]).Send("(" + DateTime.Now.ToString("H:m:s") + ") " + login + ": " + msg[2]);
                            response = "[OK] msg send";
                            break;
                        case "who":
                            response = "[OK] ";
                            foreach (object o in connectionPool.UserConnections.Values)
                            {
                                response += (string)o + ";";
                            }
                            break;
                        case "logout": response = "[OK] try close"; break;
                    }
                }
                connectionPool.GetUserConnection(login).Send(response);
            }
            catch
            {
                connectionPool.RemoveConnection(login);
                room["Default"].Remove(login);
            }
        }

        private void WelcomeNewUser(IConnectionIO conn)
        {
            string[] msg = conn.Recv().Split(' ');
            if (msg.Length == 2)
            {
                string login = msg[1];

                if (msg[0] == "login")
                {
                    if (!room["Default"].Contains(login))
                    {
                        room["Default"].Add(login);
                        connectionPool.UserConnections[conn] = login;
                        connectionPool.GetUserConnection(login).Send("[OK] Connected");
                        return;
                    }
                    else
                    {
                        conn.Send("[Exception] UserExists");
                    }
                }
                else
                {
                    conn.Send("[Exception] UnknownCommand");
                }
            }
            else
            {
                conn.Send("[Exception] UnknownCommand");
            }

            connectionPool.RemoveConnection(conn);
        }
    }
}
